import { Enum } from 'cc';
import { UITransform } from 'cc';
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

enum AutoHideType {
    Vertical,
    Horizon,
    Mixed
}

@ccclass('AutoHide')
export class AutoHide extends Component {
    @property(Node)
    private ndTarget: Node = null;
    @property({ type: Enum(AutoHideType), tooltip: '自动隐藏检测模式' })
    private mode: AutoHideType = AutoHideType.Mixed;

    private _isVisible: boolean = true;

    public set Target(node: Node) {
        this.ndTarget = node;
    }

    public isHide(): void {
        const currentNode = this.getNodeBounds(this.node);
        const targetNode = this.getNodeBounds(this.ndTarget);

        let isVisible: boolean = true;
        switch (this.mode) {
            case AutoHideType.Vertical:
                isVisible = this.checkVerticalVisibility(currentNode, targetNode);
                break;
            case AutoHideType.Horizon:
                isVisible = this.checkHorizonVisibility(currentNode, targetNode);
                break;
            case AutoHideType.Mixed:
                isVisible = this.checkVerticalVisibility(currentNode, targetNode) &&
                    this.checkHorizonVisibility(currentNode, targetNode);
                break;
        }

        if (isVisible !== this._isVisible) {
            this._isVisible = isVisible;
            this.node.active = isVisible;
            // console.log(`${this.node.name} isVisible:${isVisible}`);
        }
    }

    private getNodeBounds(node: Node): { left: number, right: number, bottom: number, top: number } {
        const worldPos = node.getWorldPosition();
        const size = node.getComponent(UITransform).contentSize;
        const anchor = node.getComponent(UITransform).anchorPoint;

        const left = worldPos.x - size.width * anchor.x;
        const right = left + size.width;
        const bottom = worldPos.y - size.height * anchor.y;
        const top = bottom + size.height;

        return { left, right, bottom, top };
    }

    private checkVerticalVisibility(currentNode: { bottom: number, top: number }, targetNode: { bottom: number, top: number }): boolean {
        return currentNode.bottom <= targetNode.top && targetNode.bottom <= currentNode.top;
    }

    private checkHorizonVisibility(currentNode: { left: number, right: number }, targetNode: { left: number, right: number }): boolean {
        return currentNode.left <= targetNode.right && targetNode.left <= currentNode.right;
    }
}